package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/admin/storage")
public class AdminStorageController {

    @Autowired
    DtsStorageService storageService;

//    @RequestMapping("/delete")
//    public Object delete(@RequestBody DtsStorage storage){
//
//        storageService.deleteById(storage);
//        return ResponseUtil.ok();
//
//    }
//    @RequestMapping("update")
//    public Object update(@RequestBody DtsStorage storage){
//        storageService.update(storage);
//        return ResponseUtil.ok(storage);
//    }

    @RequestMapping("/create")
    public Object add(MultipartFile file) throws Exception {

        String originalFilename =  file.getOriginalFilename();//获取原始文件名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        DtsStorage storage = storageService.insert(ext,(int)file.getSize(),file.getBytes());
        return ResponseUtil.ok(storage);
    }


    @GetMapping("/list")
    public Object list(
            @RequestParam(name="page", required = false, defaultValue = "1") Integer page,
            @RequestParam(name="limit", required = false, defaultValue = "20") Integer limit,
            String key,
            String name,
            @RequestParam(name="sort", required = false, defaultValue = "add_time") String sort,
            @RequestParam(name="order", required = false, defaultValue = "asc") String order
    ){
        IPage<DtsStorage> ipage = storageService.queryPage(page, limit ,key, name ,sort, order);

        Map<String,Object> data = new HashMap<>();
        data.put("total", ipage.getTotal());
        data.put("items", ipage.getRecords());
        return ResponseUtil.ok(data);
    }
    @PostMapping("update")
    public Object update(@RequestBody DtsStorage storage){
        if(storage == null){
            return ResponseUtil.badArgument();
        }
        int dts = storageService.update(storage);
        if(dts == 0){
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(storage);
    }

    @PostMapping("delete")
    public Object delete(@RequestBody DtsStorage storage){
        if(storage == null){
            return ResponseUtil.badArgument();
        }
        int dts = storageService.delete(storage);
        if(dts == 0){
            return ResponseUtil.fail(-1,"更新失败");
        }
        return ResponseUtil.ok();
    }
}
